package team.scau.laboratory_repair.common.aspect;

import lombok.extern.apachecommons.CommonsLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import team.scau.laboratory_repair.common.exception.IdNotExitException;
import team.scau.laboratory_repair.common.exception.ListEmptyException;
import team.scau.laboratory_repair.common.json.StatusCode;
import team.scau.laboratory_repair.common.json.Result;

/**
 * @Description:捕获从服务层抛出已知的异常
 * @Author:ZTF
 * @Date:2018/5/23 15:32
 */
@Aspect
@Component
@CommonsLog
public class ControllerAspect {
    @Pointcut("execution(public team.scau.laboratory_repair.common.json.Result *(..))")
    public void serviceException(){}

    @Around("serviceException()")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();
        Result result=null;
        try {
            result = (Result) pjp.proceed();
            log.info(pjp.getSignature() + " 执行时间为:" + (System.currentTimeMillis() - startTime));
            return result;
        } catch (Exception e) {
            //执行异常处理过程
            return handlerException(pjp, e);
        } catch (Throwable throwable) {
            result.setStatusCode(StatusCode.FATAL_ERROR);
            result.setSuccess(false);
            log.error(pjp.getSignature() + " 抛出Throwable:" + throwable.getMessage());
        }
        return result;
    }

    private Result handlerException(ProceedingJoinPoint pjp, Throwable e) {
        Result result = new Result();
        // 所有已知异常
        result.setSuccess(false);
        if (e instanceof IdNotExitException) {
            result.setStatusCode(StatusCode.ID_NOT_FOUND);
        } else if(e instanceof ListEmptyException) {
            result.setStatusCode(StatusCode.LIST_EMPTY);
        }else {
            log.error(pjp.getSignature() + " 发生严重未知错误： ", e);
            result.setStatusCode(StatusCode.FATAL_ERROR);
        }
        return result;
    }
}


